package org.apache.ibatis.common.logging.slf4j;

import org.apache.ibatis.common.logging.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
import org.slf4j.spi.LocationAwareLogger;

/**
 * @Name Slf4jImpl
 * @Description: [slf4j 日志框架] 实现类
 * 描述信息：该类是一个典型的对象适配器。
 * 它的内部持有一个 “org.slf4j.Logger” 对象，所有方法都将操作委托了给该对象。
 * @Version v1.0.0
 * @Author: lichao
 * @Date: 2024-05-15 15:54:48
 **/
public class Slf4jImpl implements Log {
    private Log log;

    public Slf4jImpl(String clazz) {
        Logger logger = LoggerFactory.getLogger(clazz);
        if (logger instanceof LocationAwareLogger) {
            try {
                // 检查 slf4j >= 1.6 的方法签名
                logger.getClass().getMethod("log", Marker.class, String.class, int.class, String.class, Object[].class, Throwable.class);
                log = new Slf4jLocationAwareLoggerImpl((LocationAwareLogger) logger);
                return;
            } catch (SecurityException | NoSuchMethodException e) {
                // 遇到异常，使用 Slf4jLoggerImpl 包装类
            }
        }
        // Logger 不是 LocationAwareLogger 或者 slf4j < 1.6
        log = new Slf4jLoggerImpl(logger);
    }

    @Override
    public boolean isDebugEnabled() {
        return log.isDebugEnabled();
    }

    @Override
    public boolean isTraceEnbaled() {
        return log.isTraceEnbaled();
    }

    @Override
    public void error(String msg, Throwable e) {
        log.error(msg, e);
    }

    @Override
    public void error(String msg) {
        log.error(msg);
    }

    @Override
    public void warn(String msg) {
        log.warn(msg);
    }

    @Override
    public void debug(String msg) {
        log.debug(msg);
    }

    @Override
    public void trace(String msg) {
        log.trace(msg);
    }
}

